﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.BusinessData.Administration;
using System.Data.SqlClient;
using CNRS.CCP.Connector;
using Microsoft.SharePoint.Administration;

namespace CNRS.CCP.DAO
{
    public class BaseDAO
    {
        #region Field
        /// <summary>
        /// String de connexion à la base SQL
        /// </summary>
        protected string _connection;

        /// <summary>
        /// Table dédiée
        /// </summary>
        protected string _table;
        #endregion

        #region Constructors
        public BaseDAO(string connection, string table)
        {
            if (string.IsNullOrEmpty(connection))
                throw new ArgumentNullException("connection string is empty");
            _connection = connection;
            _table = table;
        }
        #endregion

        #region Methods
        /// <summary>
        /// Récupère la liste d'item
        /// </summary>
        /// <returns></returns>
        public List<DataElement> GetItems(DAOParameter whereParameter)
        {
            List<DataElement> items = new List<DataElement>();

            using (SqlConnection connexion = new SqlConnection())
            {
                connexion.ConnectionString = _connection;
                connexion.Open();

                SqlCommand cmd = connexion.CreateCommand();
                cmd.CommandText = BuildGetCommand(cmd, whereParameter);
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                        items.Add(WrapItem(dr));
                }

                connexion.Close();
            }
            return items;
        }

		private string BuildGetCommand(SqlCommand command, DAOParameter whereParameter)
        {
            StringBuilder sb = new StringBuilder();
            //whereParameter.Value = "%" + whereParameter.Value + "%";
            command.Parameters.AddWithValue(whereParameter.ParameterName, whereParameter.Value);
            sb.AppendFormat("SELECT {1} FROM [{0}] WHERE {1} LIKE {2}", _table, whereParameter.Column, whereParameter.ParameterName);

            return sb.ToString();
        }

        /// <summary>
        /// Wrap un item en objet
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private DataElement WrapItem(SqlDataReader data)
        {
            DataElement element = new DataElement();

            element.Value = data[0].ToString();

            return element;
        }
        #endregion


    }
}
